package com.example.alarmclock;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_SCHEDULE_EXACT_ALARM = 1001;
    private ListView alarmListView;
    private Button addButton;
    private ArrayAdapter<String> adapter;
    private List<AlarmModel> alarms = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        alarmListView = findViewById(R.id.alarm_list_view);
        addButton = findViewById(R.id.add_button);

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getDisplayList());
        alarmListView.setAdapter(adapter);

        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AlarmDetailActivity.class);
                startActivityForResult(intent, 1);
            }
        });

        alarmListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AlarmModel selectedAlarm = alarms.get(position);
                Intent intent = new Intent(MainActivity.this, AlarmDetailActivity.class);
                intent.putExtra("alarm", selectedAlarm.toString());
                intent.putExtra("position", position);
                startActivityForResult(intent, 2);
            }
        });

        // Request runtime permissions for SCHEDULE_EXACT_ALARM and USE_EXACT_ALARM
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.SCHEDULE_EXACT_ALARM) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.USE_EXACT_ALARM) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.SCHEDULE_EXACT_ALARM, Manifest.permission.USE_EXACT_ALARM},
                        REQUEST_CODE_SCHEDULE_EXACT_ALARM);
            }
        }
    }

    private List<String> getDisplayList() {
        List<String> displayList = new ArrayList<>();
        for (AlarmModel alarm : alarms) {
            displayList.add(alarm.getLabel() + " (" + alarm.getTimeString() + ")");
        }
        return displayList;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_SCHEDULE_EXACT_ALARM) {
            boolean allGranted = true;
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            if (allGranted) {
                // Permissions granted
            } else {
                // Permissions denied
                Toast.makeText(this, "权限被拒绝，无法设置精确闹钟", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            String alarmInfo = data.getStringExtra("alarm_info");
            AlarmModel alarm = AlarmModel.fromString(alarmInfo);

            if (requestCode == 1) { // Add new alarm
                alarms.add(alarm);
                AlarmHelper.setAlarm(this, alarm.getHour(), alarm.getMinute(), alarm.getId());
            } else if (requestCode == 2) { // Edit existing alarm
                int position = data.getIntExtra("position", -1);
                if (position != -1) {
                    AlarmModel oldAlarm = alarms.get(position);
                    AlarmHelper.cancelAlarm(this, oldAlarm.getId());
                    alarms.set(position, alarm);
                    AlarmHelper.setAlarm(this, alarm.getHour(), alarm.getMinute(), alarm.getId());
                }
            }
            adapter.clear();
            adapter.addAll(getDisplayList());
        }
    }
}



